/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.notaria.guerrasalas.resources;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.sql.Connection;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRPdfExporterParameter;
import net.sf.jasperreports.j2ee.servlets.ImageServlet;

/**
 *
 * @author Administrador
 */
public class ReportUtil implements Serializable {

    private String rutaReportes;

    public ReportUtil() {
    }

    public String generarReporte(String nombreReporte, TipoReporte tipoReporte, Collection dataSource, HashMap parametros, FacesContext facesContext, boolean dialogoDescarga) throws Exception {
        return generarReporte(nombreReporte, tipoReporte, dataSource, parametros, facesContext, dialogoDescarga, null);
    }

    public String generarReporte(String nombreReporte, TipoReporte tipoReporte, Collection dataSource, HashMap parametros, FacesContext facesContext, boolean dialogoDescarga, Connection conexion) throws Exception {

        ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
        HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest();

        response.setContentType(tipoReporte.getContentType());
        String header = "filename=\"" + nombreReporte + tipoReporte.getExtension() + "\"";
        if (dialogoDescarga) {
            header = "attachment;" + header;
        }
        response.setHeader("Content-disposition", header);
        rutaReportes = servletContext.getRealPath("/WEB-INF/reportes/");
        parametros.put("RUTA_IMAGENES", servletContext.getRealPath("/images/"));
        JasperPrint jprint;
        if (conexion == null) {
            jprint = JasperFillManager.fillReport(loadReportFile(nombreReporte),
                    parametros,
                    (dataSource != null && dataSource.isEmpty()) ? new JREmptyDataSource() : new JRBeanCollectionDataSource(dataSource));
        } else {
            jprint = JasperFillManager.fillReport(loadReportFile(nombreReporte), parametros, conexion);
        }
        Map imagesMap = new HashMap();
        facesContext.getExternalContext().getSessionMap().put("IMAGES_MAP", imagesMap);
        request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jprint);
        switch (tipoReporte) {
            case PDF:
                pdfExport(jprint, response);
                break;
            case HTML:
                htmlExport(jprint, response, imagesMap);
                break;
        }
        if (conexion != null) {
            try {
                conexion.close();
            } catch (Exception ignored) {
                //Se ignora la excepcion
            }
        }
        facesContext.responseComplete();
        return "";
    }

    private JRExporter createConfigHTMLExporter(JasperPrint jprint, HttpServletResponse response, Map imagesMap) throws IOException {
        JRExporter exporter = new JRHtmlExporter();
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jprint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
        exporter.setParameter(JRHtmlExporterParameter.IMAGES_MAP, imagesMap);
        //exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, "images?image=");
        exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
        exporter.setParameter(JRHtmlExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.FALSE);
        exporter.setParameter(JRHtmlExporterParameter.SIZE_UNIT, "px");
        exporter.setParameter(JRHtmlExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
        exporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, Boolean.TRUE);
//        File f = new File("C:\\images");
//        exporter.setParameter(JRHtmlExporterParameter.IMAGES_DIR, f);
//        exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, "C:\\images\\");
        return exporter;
    }

    private JRExporter createConfigPDFExporter(JasperPrint jprint, HttpServletResponse response) throws IOException {
        JRExporter exporter = new JRPdfExporter();
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jprint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
        exporter.setParameter(JRPdfExporterParameter.IS_COMPRESSED, Boolean.TRUE);
        return exporter;
    }

    private InputStream loadReportFile(String nombreReporte) throws IOException {
        File reporte = new File(rutaReportes + "\\" + nombreReporte + ".jasper");
        if (reporte.exists()) {
            return new FileInputStream(reporte);
        } else {
            throw new IOException("El reporte " + nombreReporte + ".jasper no existe.");
        }
    }

    private void pdfExport(JasperPrint jprint, HttpServletResponse response) throws IOException, JRException {
        JRPdfExporter pdfExporter = (JRPdfExporter) createConfigPDFExporter(jprint, response);
        pdfExporter.exportReport();
    }

    private void htmlExport(JasperPrint jprint, HttpServletResponse response, Map imagesMap) throws IOException, JRException {
        JRHtmlExporter htmlExporter = (JRHtmlExporter) createConfigHTMLExporter(jprint, response, imagesMap);
        htmlExporter.exportReport();
    }
}
